import React, { Component } from 'react'
import store from '../../redux/store'
import { createDecrementAction, createIncrementAction } from '../../redux/count_action'

export default class Count extends Component {
  state = {
    count: 99,
  }

  // componentDidMount() {
  //   //监测redux，只要redux中状态变化，就调用render
  //   store.subscribe(() => {
  //     this.setState({});
  //   })
  // }

  increment = () => {
    const { value } = this.selectNumber;
    store.dispatch(createIncrementAction(Number(value)));
  }

  decrement = () => {
    const { value } = this.selectNumber;
    store.dispatch(createDecrementAction(Number(value)));
  }

  incrementIfOdd = () => {
    const { value } = this.selectNumber;
    const count = store.getState();
    count % 2 === 1 && store.dispatch(createIncrementAction(Number(value)));
  }

  incrementAsync = () => {
    setTimeout(() => {
      const { value } = this.selectNumber;
      store.dispatch(createIncrementAction(Number(value)));
    }, 500)
  }

  render() {
    return (
      <div>
        <h1>当前求和为:{store.getState()}</h1>
        <select ref={c => this.selectNumber = c} name="" id="">
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>
        <button onClick={this.increment}>+</button>
        <button onClick={this.decrement}>-</button>
        <button onClick={this.incrementIfOdd}>当前为奇数加</button>
        <button onClick={this.incrementAsync}>异步加</button>
      </div>
    )
  }
}
